<?php

namespace App\Models;

use Illuminate\Notifications\Notifiable;
use Illuminate\Foundation\Auth\User;
use Laravel\Passport\HasApiTokens;

class Customer extends User
{
    use HasApiTokens, Notifiable;

    protected $dates = [
        'verify_at'
    ];

    protected $fillable = [
        'mobile', 'email', 'group_id', 'username',
    ];

    protected static function boot()
    {
        parent::boot();

        static::creating(function ($model) {
            $model->username = 'guest_' . str_random();
        });
    }

    public function findForPassport($username)
    {
        return Customer::query()->where('username', $username)->first();
    }

    public function carts()
    {
        return $this->hasMany(Cart::class)->latest('updated_at');
    }

    public function addresses()
    {
        return $this->hasMany(UserAddress::class)->latest('is_default');
    }

    public function invoices()
    {
        return $this->hasMany(Invoice::class);
    }

    public function orders()
    {
        return $this->hasMany(Order::class);
    }

    public function avatar()
    {
        return $this->hasOne(Image::class, 'type_id')
            ->where('type', Image::CUSTOMER_AVATAR);
    }

    public function collections()
    {
        return $this->belongsToMany(Product::class, 'collections')
            ->as('collections')
            ->withTimestamps();
    }

    public function pocket()
    {
        return $this->hasOne(Pocket::class)->withDefault([
            'amount' => 0,
        ]);
    }

    public function getAddresses()
    {
        return $this->addresses;
    }

    public function detail()
    {
        return $this->hasOne(CustomerDetail::class)->withDefault([
            'nickname' => null,
            'summary' => '这个家伙很懒，什么都没有留下！',
            'sex' => 0,
        ]);
    }

    public function group()
    {
        return $this->belongsTo(Group::class)->withDefault([
            'name' => '普通会员',
        ]);
    }

    public function getCollectionProductIdsAttribute()
    {
        return $this->collections->pluck('id')->toArray();
    }
}
